import { serviceContext } from '@/service/context'
import { E_ERROR_CODE } from '@/service/typing/enum/error-code'
import { IUserInfo } from '@/service/typing/service/IUserService'
import produce from 'immer'
import { Dispatch } from 'redux'
import { E_A_USER_TYPE } from '../action-types'
import { IAction } from '../store-types'
import { createAction } from '../store-util'

export interface IUserState {
  userInfo?: IUserInfo
}

const initialState: IUserState = {
  userInfo: undefined
}

export interface IUserAction {
  getUserInfo(): Promise<void>
  setUserInfo(userInfo?: IUserInfo): void
}

export const getUserInfo = () => async (dispatch: Dispatch) => {
  const result = await serviceContext.get().user.getUserInfo()
  if (result.errorCode === E_ERROR_CODE.SUCCESS) {
    dispatch(createAction(E_A_USER_TYPE.SET_USER_INFO, result.data))
  }
}

export const setUserInfo = (userInfo?: IUserInfo) => (dispatch: Dispatch) => {
  dispatch(createAction(E_A_USER_TYPE.SET_USER_INFO, userInfo))
}

export default function reducer(state: IUserState = initialState, action: IAction) {
  switch (action.type) {
    case E_A_USER_TYPE.SET_USER_INFO:
      return produce(state, draft => {
        draft.userInfo = action.payload as IUserInfo
      })
    default:
      return state
  }
}

declare module '../store-types' {
  interface IGlobalState {
    user: IUserState
  }
}
